import { XlsxService } from './../../services/xlsx.service';
import { DeleteService } from './../../services/delete.service';
import { Injectable } from '@nestjs/common';
import { MailDbService } from './mail.db.services';
import * as fs from 'fs';

@Injectable()
export class MailService {
  constructor(
    public mailDbService: MailDbService,
    public deleteService: DeleteService,
    public xlsxService: XlsxService,
  ) { }
  async uploadMail(params) {
    const userMail = this.getMap(params);
    // console.log(userMail);
    await this.mailDbService.create({ name: '邮箱', userMail: userMail });
  }

  getMap(params) {
    let nameList = [];
    let mailList = [];
    let userMail = {};
    for (let i in params) {
      if (i.indexOf('name') > -1) {
        nameList.push(i);
      } else {
        mailList.push(i);
      }
    }
    nameList.forEach((value, index) => {
      userMail[params[nameList[index]]] = params[mailList[index]];
    })
    return userMail;
  }
  async find() {
    return await this.mailDbService.find();
  }
  async deleteMail(name: string) {
    return await this.mailDbService.deleteMail(name);
  }

  async uploadPayroll(file) {
    const xlsx = new Buffer(file.buffer, 'base64');
    const writerStream = fs.createWriteStream('src/payroll/payroll.xlsx');
    writerStream.write(xlsx);
    writerStream.end();


    const data = await new Promise(resolve => {
      writerStream.on('finish', () => {
          console.log('写入完成。');
          resolve(this.xlsxService.gotPayroll('src/payroll'));
      });
  });
  return data;
  }
}